package component

import (
	"github.com/topfreegames/pitaya/logger"
	"github.com/topfreegames/pitaya/util"
)

type (
	LogicThread struct {
		Base
		Name string
		option options
		DieChan chan struct{}
		Run func()
		alive bool
		id uint64
	}

	Runnable interface {
		Component
		SetName(opts []Option)
		GetName() string
		IsAlive() bool
		ID() uint64
	}
)

func (p *LogicThread) SetName(opts []Option)  {
	for _,opt := range opts {
		opt(&p.option)
	}

	if name := p.option.name;name != "" {
		p.Name = name
	}
}

func (p *LogicThread) GetName() string {
	return p.Name
}

func (p *LogicThread) Init()  {
	go func() {
		p.id = util.GetGoroutineID()
		for {
			select {
			case <- p.DieChan:
				logger.Log.Infof("线程%s关闭",p.Name)
				close(p.DieChan)
				p.alive = false
				return
			default:
				p.Run()
			}
		}
	}()
	p.alive = true
}

func (p *LogicThread) Shutdown()  {
	p.DieChan <- struct{}{}
}

/**
判断线程是否关闭
 */
func (p *LogicThread) IsAlive() bool {
	return p.alive
}

func (p *LogicThread) ID() uint64 {
	return p.id
}







